#include "attachRev.h"

map<int, bool> in_use;

void attachRev(list<libusb_device_handle*> &rev_handles){

    libusb_device **devices = NULL;

    ssize_t count = libusb_get_device_list(NULL, &devices);

    //获取所有usb总线的设备
    for(int dev_idx = 0; dev_idx < count; ++dev_idx){

        libusb_device * dev = devices[dev_idx];
        libusb_device_descriptor desc;
        //通过usb设备描述符进行筛选
        if(libusb_get_device_descriptor(dev, &desc) == 0){
            if( (unsigned short)desc.idVendor == (unsigned short)SILICON_LABS_VENDOR_ID &&
                (unsigned short)desc.idProduct == (unsigned short)SILICON_LABS_PRODUCT_ID){
                    
                int rev_code = 0x100 * libusb_get_bus_number(dev) + libusb_get_device_address(dev);

                if(in_use[rev_code] != true){
                    puts("get a usb connector");
                    libusb_device_handle *new_handle;
                    if(libusb_open(dev, &new_handle) == 0){
                       if(libusb_reset_device(new_handle) == 0){
                            rev_handles.push_back(new_handle);
                            puts("new Receive opened");
                            in_use[rev_code] = true;

                            int retval = libusb_set_configuration(rev_handles.back(), 1);
                            
                            if(retval != 0){
                                puts("setting configuration to 1 failed");
                            }else{
                                int interface_num = 0;
                                if(libusb_kernel_driver_active(rev_handles.back(), interface_num)){
                                    libusb_detach_kernel_driver(rev_handles.back(),interface_num);
                                }

                                if(libusb_claim_interface(rev_handles.back(), 0 ) != 0)
                                    puts("claim interface failed");
                            }
                        }
                    }
                    else{
                        puts("open device failed ,try sudo");
                    }
                    
                }
            }
        }
    }

    libusb_free_device_list(devices, true);
    return;
}
